<?php

namespace App\Morefun\Activity;

use App\Contracts\Services\Storage\StorageService;
use App\Entities\Activity;
use App\Morefun\Publishing\Publisher;
use Illuminate\Container\Container;
use Illuminate\Support\Arr;

abstract class RedisSynchronizerBase
{
    protected $redis;

    abstract function write(Activity $activity);

    public function translateActivitySummary(Activity $activity)
    {
        $storage = Container::getInstance()->make(StorageService::class);
        $id = $activity->getAttribute('id');
        $shares = json_decode($activity->getAttribute('shares'), true);
        
        return [
            'id' => $id,
            'name' => $activity->getAttribute('name'),
            'start_at' => $activity->getAttribute('startTime'),
            'end_at' => $activity->getAttribute('endTime'),
            'description' => $activity->getAttribute('description'),
            //'background_img' => $storage->toHttpUrl($activity->getAttribute('backgroundImg')),
            //'background_color' => $activity->getAttribute('backgroundColor'),
            'list_background_img' => $storage->toHttpUrl($activity->getAttribute('listBackgroundImg')),
            'rules' => json_decode($activity->getAttribute('rule')),
            'app_url' => $activity->getAttribute('app_url'),
            'publishing' => (new Publisher)->formatJsonString($activity->getAttribute('publishing_ways')),
            'shares' => [
                'isopen' => Arr::get($shares, 'isopen', 'off'),
                'title' => Arr::get($shares, 'title', ''),
                'content' => Arr::get($shares, 'content', ''),
                'thumb' => $storage->toHttpUrl(Arr::get($shares, 'icon', '')),
            ],
        ];
    }

    public function writeRules(Activity $activity)
    {
        $id = $activity->getAttribute('id');
        $limits = \GuzzleHttp\json_decode($activity->getAttribute('limit'), true);

        $this->redis()->hmset(sprintf('rules:%s', $id),
            'is_paused', $activity->getAttribute('isPause'),
            'start_at', strtotime($activity->getAttribute('startTime')),
            'end_at', strtotime($activity->getAttribute('endTime')),
            'limit_type', Arr::get($limits, 'type', 'day'),
            'limit_times', Arr::get($limits, 'num', 0)
        );
    }

    /**
     * @return \Redis
     */
    protected function redis()
    {
        if (null === $this->redis){
            $this->redis = Container::getInstance()->make('redis');
        }
        return $this->redis;
    }
}
